package com.dna.okangjang.main.dao.rest;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import com.dna.okangjang.main.dao.DaumApiDao;
import com.dna.okangjang.main.model.DBlog;
import com.dna.okangjang.main.model.DCafe;
import com.dna.okangjang.main.model.DImage;

@Repository("daumApiDao")
public class DaumApiDaoRest implements DaumApiDao {
	private static final Log logger = LogFactory.getLog(DaumApiDaoRest.class);
	
	private static final String BLOG_SEARCH_API = "http://apis.daum.net/search/blog";
	private static final String CAFE_SEARCH_API = "http://apis.daum.net/search/cafe";
	private static final String IMG_SEARCH_API = "http://apis.daum.net/search/image";
	private static final String API_KEY = "fce97a9baec921d7a5f1d8f66018b2805a2f3e65";
	
	@Resource
	private RestTemplate restTemplate;
	
	@Override
	public List<DBlog> getSearchBlog(String query, int page, int row) {
		return this.getResult(DBlog.class, query, page, row);
	}
	
	@Override
	public List<DCafe> getSearchCafe(String query, int page, int row) {
		return this.getResult(DCafe.class, query, page, row);
	}
	
	@Override
	public List<DImage> getSearchImage(String query, int page, int row) {
		return this.getResult(DImage.class, query, page, row);
	}
	
	protected <T> List<T> getResult(Class<T> clz, String query, int page, int row){
		String prefix = null;
		if(clz.equals(DBlog.class)){
			prefix = BLOG_SEARCH_API;
		} else if(clz.equals(DCafe.class)){
			prefix = CAFE_SEARCH_API;
		} else if(clz.equals(DImage.class)){
			prefix = IMG_SEARCH_API;
		}
		
		String enc_query = null;
		try {
			enc_query = URLEncoder.encode(query, "utf-8");
		} catch (UnsupportedEncodingException e1) {
			logger.error(">>> encoding error");
		}
		
		String api_url = new StringBuffer(prefix).append("?")
				.append("apikey=").append(API_KEY).append("&q=").append(enc_query)
				.append("&pageno=").append(page).append("&result=").append(row)
				.append("&output=json").append((clz.equals(DImage.class)?"&sort=accu":"")).toString();
		//logger.debug(">>> api_url : " + api_url);
		
		String str = null;
		try{
			str = restTemplate.getForObject(new URI(api_url), String.class);
		} catch(RestClientException e){
			logger.error(">>> search error");
		} catch(URISyntaxException e){
			logger.error(">>> search error");
		}
		
		List<T> list = new ArrayList<T>();
		if(str != null){
			try{
				JSONObject obj = JSONObject.fromObject(str);
				obj = obj.getJSONObject("channel");
				JSONArray arr = obj.getJSONArray("item");
				for(int i=0; i<arr.size(); i++){
					@SuppressWarnings("unchecked")
					T model = (T) JSONObject.toBean(arr.getJSONObject(i), clz);
					list.add(model);
				}
			} catch(Exception e){
				e.printStackTrace();
			}
		}
		
		return list;
	}

}
